﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Win32;
using nwrole.lib;

namespace nwrole.lib2 {
    public class Configuration {
        private static string applicationDirectory;
        //private static string applicationDirectoryPath;
        public static string ApplicationExe = "nwrole.service.exe"; // TODO: move this?
        public static string PluginServiceExe = "nwrole.pluginservice.exe"; // TODO: move this?

        /*private static List<PluginData> PluginDatas = new List<PluginData>();
        private static List<ServiceData> ServiceDatas = new List<ServiceData>();*/

        private static void WriteLog(string content) {
            DateTime now = DateTime.Now;
            var path = "c:/log/nwrole/PluginService/";
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            System.IO.File.AppendAllText(path + "log " + now.ToString("yyyy-MM-dd") + ".txt", now.ToString("yyyy-MM-dd hh:mm:ss ") + content + "\r\n");
        }

        #region Loading and saving
        public static void Load() {

            applicationDirectory = Path.GetDirectoryName( Assembly.GetEntryAssembly().Location );
            //applicationDirectory = Path.GetFileName(applicationDirectoryPath);
            //RegistryKey rkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Systeam E AB\\nwrole Supervisor Service");
            //applicationDirectory = rkey.GetValue("InstallationPath").ToString();
            //rkey.Close();

            /*WriteLog("appdir: " + applicationDirectory);

            //CheckForPlugins();

            ////

            string servicesDir = Configuration.ServicesDirectory;
            if (!Directory.Exists(servicesDir))
                Directory.CreateDirectory(servicesDir);

            ServiceDatas.Clear();

            foreach (string serviceDir in Directory.EnumerateDirectories(servicesDir)) {

                ServiceData serviceData = null;

                string configPath = Path.Combine(serviceDir, "service-config.xml");

                try {
                    if (File.Exists(configPath)) {
                        PropertyList plist = new PropertyList(configPath);
                        serviceData = StorageUtil.ServiceDataFromDictionary((IDictionary) plist.DictionaryForKey("Service"));
                    }
                } catch(Exception e) {
                    serviceData = null;
                }

                if(serviceData == null) {
                    serviceData = new ServiceData();
                    serviceData.Name = Path.GetFileName(serviceDir);
                    serviceData.Id = Guid.NewGuid();
                    serviceData.Enabled = false;
                    //serviceData.PluginDatas = new List<PluginData>();

                    PropertyList plist = new PropertyList();
                    plist["Service"] = StorageUtil.ServiceDataToDictionary(serviceData);
                    
                    plist.Save(configPath);
                }

                ServiceDatas.Add(serviceData);
            }

            ////

            if (!File.Exists(ConfigurationFilePath))
                return;*/

        }

        public static void Save() {
            /*try {
                Directory.CreateDirectory(ConfigurationDirectoryPath);

                string servicesDir = Configuration.ServicesDirectory;
                if (!Directory.Exists(servicesDir))
                    Directory.CreateDirectory(servicesDir);

                foreach(ServiceData serviceData in ServiceDatas) {
                    string serviceDir = Path.Combine(servicesDir, serviceData.Name);
                    string configPath = Path.Combine(serviceDir, "service-config.xml");

                    PropertyList plist = new PropertyList();
                    plist["Service"] = StorageUtil.ServiceDataToDictionary(serviceData);

                    plist.Save(configPath);
                }

            } catch (Exception exception) {
                EventLogger.LogException("Configuration.Save", exception);
            }*/
        }

        /*public static void CheckForPlugins_XXX() {
            string servicesDir = Configuration.ServicesDirectory;
            if (!Directory.Exists(servicesDir))
                Directory.CreateDirectory(servicesDir);

            foreach (string serviceDir in Directory.EnumerateDirectories(servicesDir)) {
                Guid serviceId;
                bool enabled = false;
                List<PluginData> pluginDatas = new List<PluginData>();

                string configPath = Path.Combine(serviceDir, "service-config.xml");
                if (File.Exists(configPath)) {
                    PropertyList plist = new PropertyList(configPath);
                    serviceId = new Guid(plist.StringForKey("ServiceId"));
                    enabled = plist.BooleanForKey("Enabled");

                    foreach (object dict in plist.ArrayForKey("Plugins"))
                        pluginDatas.Add(StorageUtil.PluginDataFromDictionary((IDictionary)dict));
                }
                else {
                    serviceId = Guid.NewGuid();

                    PropertyList plist = new PropertyList();
                    plist["DisplayName"] = Path.GetFileName(serviceDir);
                    plist["ServiceId"] = serviceId.ToString("N");
                    plist["Enabled"] = enabled;
                    plist["Plugins"] = pluginDatas;

                    plist["Plugins"] = new List<object>();
                    foreach (PluginData pluginData in PluginDatas)
                        plist.ArrayForKey("Plugins").Add(StorageUtil.PluginDataToDictionary(pluginData));

                    plist.Save(configPath);
                }

                ServiceData serviceData = ServiceDatas.SingleOrDefault(d => d.Id.Equals(serviceId));
                if (serviceData == null) {
                    serviceData = new ServiceData();
                    serviceData.Name = Path.GetFileName(serviceDir);
                    serviceData.Id = serviceId;
                    serviceData.Enabled = enabled;
                    //serviceData.PluginDatas = pluginDatas;
                    ServiceDatas.Add(serviceData);
                }
            }
        }*/
        #endregion

        #region Paths
        public static string RootDirectoryPath {
            //get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), ApplicationDirectory); }
            get { return applicationDirectory; }
        }

        public static string ConfigurationDirectoryPath {
            get { return Path.Combine(RootDirectoryPath, "configuration"); }
        }

        public static string ConfigurationFilePath {
            get { return Path.Combine(ConfigurationDirectoryPath, "configuration.plist"); }
        }

        public static string PluginsDirectory {
            get { return Path.Combine(RootDirectoryPath, "plugins"); }
        }

        public static string ServicesDirectory {
            get { return Path.Combine(RootDirectoryPath, "services"); }
        }

        #endregion

        /*#region Plugins
        public static PluginData PluginDataWithId(Guid id) {
            return (from pluginData in PluginDatas where pluginData.Id == id select pluginData).FirstOrDefault();
        }
        #endregion

        #region Services
        public static ServiceData ServiceDataWithId(Guid id) {
            return (from serviceData in ServiceDatas where serviceData.Id == id select serviceData).FirstOrDefault();
        }
        #endregion*/
    }
}
